package com.acme.bankapp.service.bank;

import com.acme.bankapp.domain.bank.*;
import com.acme.bankapp.domain.bank.accounts.Account;
import com.acme.bankapp.domain.bank.accounts.CheckingAccount;
import com.acme.bankapp.domain.bank.accounts.SavingAccount;
import com.acme.bankapp.exceptions.BankException;

import java.io.*;

/**
 * Created by Student on 19.11.2014.
 */
public class BankDataLoaderService {
    public static Bank loadClients(Bank bank, String path) {
        try (
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(path))));
        ) {
            String line;
            while ((line = reader.readLine()) != null) {
                bank.addClient(createClientFromString(line));
            }

        } catch (IOException | BankException e) {
            e.printStackTrace();
        }

        return bank;

    }

    private static Client createClientFromString(String line) {
        String[] values = line.split(";");
        double balance = Double.parseDouble(values[1].split("=")[1]);
        double overdraft = Double.parseDouble(values[2].split("=")[1]);
        String name = values[3].split("=")[1];
        Gender gender = (values[4].split("=")[1].charAt(0) == 'm') ? Gender.MALE : Gender.FEMALE;
        Account acc = null;
        switch (values[0].split("=")[1]) {
            case "c":
                acc = new CheckingAccount(balance, overdraft);
                break;
            case "s":
                acc = new SavingAccount(balance);
        }
        return new Client(name, gender, acc);
    }
}
